using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Net.NetworkInformation;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using WIT.DAQ.Core.Helper;
using WIT.DAQ.Core.Models;
using WIT.DAQ.Core.Properties;

namespace WIT.DAQ.Core.Forms;

/// <summary>
///
/// </summary>
internal class DeviceMgrForm : BaseForm
{
	/// <summary>
	/// 记录设备列表
	/// </summary>
	private ObservableCollection<Device> DEVICES = new ObservableCollection<Device>();

	/// <summary>
	/// 标记设备列表集合是否改变
	/// </summary>
	private bool IS_DEVICES_COLLECTIONCHANGED = false;

	/// <summary>
	/// 异步更新设备状态
	/// </summary>
	private BackgroundWorker BW_UPDATE_DEVICE_STATUS;

	/// <summary>
	/// Required designer variable.
	/// </summary>
	private IContainer components = null;

	private ContextMenuStrip cmsDevice;

	private ToolStripMenuItem tsmiDel;

	private ToolStripMenuItem tsmiEdit;

	private Button btnAdd;

	private TreeView tvDevices;

	private Button btnDel;

	private ImageList imageList;

	private ToolStripSeparator toolStripSeparator1;

	private Button btnDown;

	private Button btnUp;

	private ToolStrip toolStrip1;

	private ToolStripDropDownButton tsbtnDelayLog;

	private ToolStripMenuItem tsmiStartDelayLog;

	private ToolStripMenuItem tsmiStopDelayLog;

	private ToolStripSeparator toolStripSeparator2;

	private ToolStripMenuItem tsmiSetting;

	/// <summary>
	///
	/// </summary>
	internal DeviceMgrForm()
	{
		InitializeComponent();
	}

	private void DeviceForm_Load(object sender, EventArgs e)
	{
		ToolTip toolTip = new ToolTip();
		toolTip.AutoPopDelay = 3000;
		toolTip.InitialDelay = 500;
		toolTip.ReshowDelay = 500;
		toolTip.ShowAlways = true;
		toolTip.SetToolTip(btnAdd, "添加设备");
		ToolTip toolTip2 = new ToolTip();
		toolTip2.AutoPopDelay = 3000;
		toolTip2.InitialDelay = 500;
		toolTip2.ReshowDelay = 500;
		toolTip2.ShowAlways = true;
		toolTip2.SetToolTip(btnDel, "删除设备");
		ToolTip toolTip3 = new ToolTip();
		toolTip3.AutoPopDelay = 3000;
		toolTip3.InitialDelay = 500;
		toolTip3.ReshowDelay = 500;
		toolTip3.ShowAlways = true;
		toolTip3.SetToolTip(btnUp, "上移");
		ToolTip toolTip4 = new ToolTip();
		toolTip4.AutoPopDelay = 3000;
		toolTip4.InitialDelay = 500;
		toolTip4.ReshowDelay = 500;
		toolTip4.ShowAlways = true;
		toolTip4.SetToolTip(btnDown, "下移");
		InitDevices();
		DEVICES.CollectionChanged += DEVICES_CollectionChanged;
		BW_UPDATE_DEVICE_STATUS = new BackgroundWorker
		{
			WorkerSupportsCancellation = true
		};
		BW_UPDATE_DEVICE_STATUS.DoWork += BW_UPDATE_DEVICE_STATUS_DoWork;
		BW_UPDATE_DEVICE_STATUS.RunWorkerAsync();
		tvDevices.HideSelection = false;
		tvDevices.DrawMode = TreeViewDrawMode.OwnerDrawText;
		tvDevices.DrawNode += TvDevices_DrawNode;
		tsmiStartDelayLog.Enabled = !MainForm.IS_DELAYLOGING;
		tsmiStopDelayLog.Enabled = MainForm.IS_DELAYLOGING;
	}

	private void DeviceMgrForm_Shown(object sender, EventArgs e)
	{
		tvDevices.SelectedNode = null;
	}

	/// <summary>
	/// 加载设备列表
	/// </summary>
	private void InitDevices()
	{
		tvDevices.Nodes.Clear();
		DEVICES = new ObservableCollection<Device>(Common.GetAllDevices());
		foreach (Device dEVICE in DEVICES)
		{
			TreeNode node = new TreeNode
			{
				Name = dEVICE.Id.ToString(),
				Text = dEVICE.ShowName,
				ToolTipText = dEVICE.Desc,
				Tag = dEVICE,
				ImageIndex = 0,
				SelectedImageIndex = 0
			};
			tvDevices.Nodes.Add(node);
		}
	}

	/// <summary>
	/// treeview的选中节点在丢失焦点后仍然保持高亮
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void TvDevices_DrawNode(object sender, DrawTreeNodeEventArgs e)
	{
		e.DrawDefault = true;
	}

	/// <summary>
	/// 异步更新各设备的通讯状态
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void BW_UPDATE_DEVICE_STATUS_DoWork(object sender, DoWorkEventArgs e)
	{
		BackgroundWorker backgroundWorker = sender as BackgroundWorker;
		int pingDeviceInterval = Common.PingDeviceInterval;
		int pingDeviceTimeout = Common.PingDeviceTimeout;
		int limit = Common.DelayLogLimit;
		Ping ping = new Ping();
		PingReply replay;
		while (!backgroundWorker.CancellationPending)
		{
			try
			{
				foreach (Device dEVICE in DEVICES)
				{
					if (backgroundWorker.CancellationPending)
					{
						return;
					}
					TreeNode[] nodes = tvDevices.Nodes.Find(dEVICE.Id.ToString(), searchAllChildren: true);
					if (nodes.Length == 1)
					{
						try
						{
							if (dEVICE.IP != null && !string.IsNullOrEmpty(dEVICE.IP))
							{
								replay = ping.Send(dEVICE.IP, pingDeviceTimeout);
								if (replay.Status == IPStatus.Success)
								{
									Invoke((Action)delegate
									{
										if (replay.RoundtripTime >= limit)
										{
											if (nodes[0].ImageIndex != 3)
											{
												nodes[0].ImageIndex = 3;
												nodes[0].SelectedImageIndex = 3;
											}
										}
										else if (nodes[0].ImageIndex != 1)
										{
											nodes[0].ImageIndex = 1;
											nodes[0].SelectedImageIndex = 1;
										}
									});
									continue;
								}
								Invoke((Action)delegate
								{
									if (nodes[0].ImageIndex != 2)
									{
										nodes[0].ImageIndex = 2;
										nodes[0].SelectedImageIndex = 2;
									}
								});
								continue;
							}
							Invoke((Action)delegate
							{
								if (nodes[0].ImageIndex != 0)
								{
									nodes[0].ImageIndex = 0;
									nodes[0].SelectedImageIndex = 0;
								}
							});
						}
						catch
						{
							if (backgroundWorker.CancellationPending || base.Disposing || base.IsDisposed)
							{
								continue;
							}
							Invoke((Action)delegate
							{
								if (nodes[0].ImageIndex != 2)
								{
									nodes[0].ImageIndex = 2;
									nodes[0].SelectedImageIndex = 2;
								}
							});
						}
						continue;
					}
					throw new Exception($"在设备列表TreeView查找到[{nodes.Length}]个Id为[{dEVICE.Id}]的设备");
				}
			}
			catch (Exception ex)
			{
				if (IS_DEVICES_COLLECTIONCHANGED)
				{
					IS_DEVICES_COLLECTIONCHANGED = false;
				}
				else if (!backgroundWorker.CancellationPending && !base.Disposing && !base.IsDisposed)
				{
					LocalLog.Error("设备管理窗口异步更新设备通讯状态时发生异常（外层try.catch）：" + ex.Message);
				}
			}
			Thread.Sleep(pingDeviceInterval);
		}
	}

	/// <summary>
	/// 设备列表集合元素变化事件
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void DEVICES_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
	{
		IS_DEVICES_COLLECTIONCHANGED = true;
	}

	/// <summary>
	/// 新增设备
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void btnAdd_Click(object sender, EventArgs e)
	{
		DeviceEditForm deviceEditForm = new DeviceEditForm(EnumFormPurpose.Add)
		{
			Icon = base.Icon,
			StartPosition = FormStartPosition.CenterParent
		};
		deviceEditForm.SaveDevice += DeviceEditForm_AddDevice;
		deviceEditForm.ShowDialog();
	}

	/// <summary>
	/// 新增设备-保存
	/// </summary>
	/// <param name="device"></param>
	private void DeviceEditForm_AddDevice(Device device)
	{
		XmlDocument xmlDocument = new XmlDocument();
		xmlDocument.Load(Common.CONFIG_FILE_FULL_PATH);
		XmlElement documentElement = xmlDocument.DocumentElement;
		XmlElement xmlElement = (XmlElement)documentElement.SelectSingleNode("Devices");
		XmlElement xmlElement2 = xmlDocument.CreateElement("Device");
		xmlElement2.SetAttribute("Name", device.Name);
		xmlElement2.SetAttribute("Id", device.Id.ToString());
		xmlElement.AppendChild(xmlElement2);
		XmlElement xmlElement3 = xmlDocument.CreateElement("Type");
		xmlElement3.InnerText = device.Type.ToString();
		xmlElement2.AppendChild(xmlElement3);
		XmlElement xmlElement4 = xmlDocument.CreateElement("Brand");
		xmlElement4.InnerText = device.Brand.ToString();
		xmlElement2.AppendChild(xmlElement4);
		XmlElement xmlElement5 = xmlDocument.CreateElement("Model");
		xmlElement5.InnerText = device.Model.ToString();
		xmlElement2.AppendChild(xmlElement5);
		XmlElement xmlElement6 = xmlDocument.CreateElement("Protocol");
		xmlElement6.InnerText = device.Protocol.ToString();
		xmlElement2.AppendChild(xmlElement6);
		XmlElement xmlElement7 = xmlDocument.CreateElement("IP");
		xmlElement7.InnerText = device.IP.ToString();
		xmlElement2.AppendChild(xmlElement7);
		XmlElement xmlElement8 = xmlDocument.CreateElement("Port");
		xmlElement8.InnerText = device.Port.ToString();
		xmlElement2.AppendChild(xmlElement8);
		XmlElement xmlElement9 = xmlDocument.CreateElement("Desc");
		xmlElement9.InnerText = device.Desc;
		xmlElement2.AppendChild(xmlElement9);
		XmlElement xmlElement10 = xmlDocument.CreateElement("Params");
		xmlElement2.AppendChild(xmlElement10);
		if (device.Suffix != null)
		{
			XmlElement xmlElement11 = xmlDocument.CreateElement("Suffix");
			xmlElement11.InnerText = device.Suffix;
			xmlElement10.AppendChild(xmlElement11);
		}
		if (device.NeedAccount.HasValue)
		{
			XmlElement xmlElement12 = xmlDocument.CreateElement("NeedAccount");
			xmlElement12.InnerText = device.NeedAccount.ToString();
			xmlElement10.AppendChild(xmlElement12);
		}
		if (device.Account != null && !string.IsNullOrEmpty(device.Account))
		{
			XmlElement xmlElement13 = xmlDocument.CreateElement("Account");
			xmlElement13.InnerText = device.Account;
			xmlElement10.AppendChild(xmlElement13);
		}
		if (device.Pwd != null && !string.IsNullOrEmpty(device.Pwd))
		{
			XmlElement xmlElement14 = xmlDocument.CreateElement("Pwd");
			xmlElement14.InnerText = device.Pwd;
			xmlElement10.AppendChild(xmlElement14);
		}
		if (device.Rack.HasValue)
		{
			XmlElement xmlElement15 = xmlDocument.CreateElement("Rack");
			xmlElement15.InnerText = device.Rack.ToString();
			xmlElement10.AppendChild(xmlElement15);
		}
		if (device.Slot.HasValue)
		{
			XmlElement xmlElement16 = xmlDocument.CreateElement("Slot");
			xmlElement16.InnerText = device.Slot.ToString();
			xmlElement10.AppendChild(xmlElement16);
		}
		if (device.DataFormat != null)
		{
			XmlElement xmlElement17 = xmlDocument.CreateElement("DataFormat");
			xmlElement17.InnerText = device.DataFormat.ToString();
			xmlElement10.AppendChild(xmlElement17);
		}
		if (device.AddressStartWithZero.HasValue)
		{
			XmlElement xmlElement18 = xmlDocument.CreateElement("AddressStartWithZero");
			xmlElement18.InnerText = device.AddressStartWithZero.ToString();
			xmlElement10.AppendChild(xmlElement18);
		}
		if (device.IsStringReverse.HasValue)
		{
			XmlElement xmlElement19 = xmlDocument.CreateElement("IsStringReverse");
			xmlElement19.InnerText = device.IsStringReverse.ToString();
			xmlElement10.AppendChild(xmlElement19);
		}
		if (device.Station.HasValue)
		{
			XmlElement xmlElement20 = xmlDocument.CreateElement("Station");
			xmlElement20.InnerText = device.Station.ToString();
			xmlElement10.AppendChild(xmlElement20);
		}
		if (device.ComPort != null)
		{
			XmlElement xmlElement21 = xmlDocument.CreateElement("ComPort");
			xmlElement21.InnerText = device.ComPort.ToString();
			xmlElement10.AppendChild(xmlElement21);
		}
		if (device.BaudRate.HasValue)
		{
			XmlElement xmlElement22 = xmlDocument.CreateElement("BaudRate");
			xmlElement22.InnerText = device.BaudRate.ToString();
			xmlElement10.AppendChild(xmlElement22);
		}
		if (device.DataBits.HasValue)
		{
			XmlElement xmlElement23 = xmlDocument.CreateElement("DataBits");
			xmlElement23.InnerText = device.DataBits.ToString();
			xmlElement10.AppendChild(xmlElement23);
		}
		if (device.StopBits.HasValue)
		{
			XmlElement xmlElement24 = xmlDocument.CreateElement("StopBits");
			xmlElement24.InnerText = device.StopBits.ToString();
			xmlElement10.AppendChild(xmlElement24);
		}
		if (device.Parity.HasValue)
		{
			XmlElement xmlElement25 = xmlDocument.CreateElement("Parity");
			xmlElement25.InnerText = device.Parity.ToString();
			xmlElement10.AppendChild(xmlElement25);
		}
		xmlDocument.Save(Common.CONFIG_FILE_FULL_PATH);
		TreeNode treeNode = new TreeNode
		{
			Name = device.Id.ToString(),
			Text = device.ShowName,
			ToolTipText = device.Desc,
			Tag = device,
			ImageIndex = 0,
			SelectedImageIndex = 0
		};
		tvDevices.Nodes.Add(treeNode);
		tvDevices.SelectedNode = treeNode;
		DEVICES.Add(device);
	}

	/// <summary>
	/// 删除设备
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void btnDel_Click(object sender, EventArgs e)
	{
		DeleteDevice();
	}

	/// <summary>
	/// 删除设备
	/// </summary>
	private void DeleteDevice()
	{
		if (tvDevices.SelectedNode == null)
		{
			MessageBox.Show("请选择一个设备", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
			return;
		}
		List<Station> allStations = Common.GetAllStations();
		Device device = (Device)tvDevices.SelectedNode.Tag;
		int num = 0;
		string text = string.Empty;
		foreach (Station item in allStations)
		{
			if (item.DAQItems.Any((DAQItem t) => t.DeviceId == device.Id))
			{
				num++;
				text += (string.IsNullOrEmpty(text) ? item.Name : ("," + item.Name));
			}
		}
		if (num > 0)
		{
			MessageBox.Show($"该设备[{device.Name}]已在{num}个站点的采集项配置中使用，不允许删除。\r站点：{text}", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
			return;
		}
		int num2 = 0;
		string text2 = string.Empty;
		foreach (Station item2 in allStations)
		{
			if (item2.DAQTasks.Any((DAQTask t) => t.SocketServerId == device.Id))
			{
				num2++;
				text2 += (string.IsNullOrEmpty(text2) ? item2.Name : ("," + item2.Name));
			}
		}
		if (num2 > 0)
		{
			MessageBox.Show($"该设备[{device.Name}]已在{num2}个站点的任务配置中使用，不允许删除。\r站点：{text2}", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
		}
		else
		{
			if (MessageBox.Show("确认删除此设备[" + device.Name + "]？", "操作提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
			{
				return;
			}
			XmlDocument xmlDocument = new XmlDocument();
			xmlDocument.Load(Common.CONFIG_FILE_FULL_PATH);
			XmlElement documentElement = xmlDocument.DocumentElement;
			XmlElement xmlElement = (XmlElement)documentElement.SelectSingleNode("Devices");
			bool flag = false;
			foreach (XmlNode item3 in xmlElement.SelectNodes("Device"))
			{
				Guid guid = new Guid(item3.Attributes["Id"].Value);
				if (guid == device.Id)
				{
					flag = true;
					xmlElement.RemoveChild(item3);
					break;
				}
			}
			if (!flag)
			{
				MessageBox.Show("未在配置文件中找到对应的节点", "异常", MessageBoxButtons.OK, MessageBoxIcon.Hand);
				return;
			}
			xmlDocument.Save(Common.CONFIG_FILE_FULL_PATH);
			tvDevices.Nodes.Remove(tvDevices.SelectedNode);
			DEVICES.Remove(device);
		}
	}

	/// <summary>
	/// 弹出编辑设备窗体
	/// </summary>
	private void ShowEditDeviceForm()
	{
		if (tvDevices.SelectedNode != null)
		{
			Device device = (Device)tvDevices.SelectedNode.Tag;
			DeviceEditForm deviceEditForm = new DeviceEditForm(EnumFormPurpose.Edit, device)
			{
				Icon = base.Icon,
				StartPosition = FormStartPosition.CenterParent
			};
			deviceEditForm.SaveDevice += DeviceEditForm_EditDevice;
			deviceEditForm.ShowDialog();
		}
	}

	/// <summary>
	/// 编辑设备-保存
	/// </summary>
	/// <param name="device"></param>
	private void DeviceEditForm_EditDevice(Device device)
	{
		XmlDocument xmlDocument = new XmlDocument();
		xmlDocument.Load(Common.CONFIG_FILE_FULL_PATH);
		XmlElement documentElement = xmlDocument.DocumentElement;
		XmlElement xmlElement = (XmlElement)documentElement.SelectSingleNode("Devices");
		bool flag = false;
		foreach (XmlNode item in xmlElement.SelectNodes("Device"))
		{
			Guid guid = new Guid(item.Attributes["Id"].Value);
			if (guid == device.Id)
			{
				item.Attributes["Name"].Value = device.Name;
				item.SelectSingleNode("Type").InnerText = device.Type.ToString();
				item.SelectSingleNode("Brand").InnerText = device.Brand.ToString();
				item.SelectSingleNode("Model").InnerText = device.Model.ToString();
				item.SelectSingleNode("Protocol").InnerText = device.Protocol.ToString();
				item.SelectSingleNode("IP").InnerText = device.IP.ToString();
				item.SelectSingleNode("Port").InnerText = device.Port.ToString();
				item.SelectSingleNode("Desc").InnerText = device.Desc;
				item.RemoveChild(item.SelectSingleNode("Params"));
				XmlElement xmlElement2 = xmlDocument.CreateElement("Params");
				item.AppendChild(xmlElement2);
				if (device.Suffix != null)
				{
					XmlElement xmlElement3 = xmlDocument.CreateElement("Suffix");
					xmlElement3.InnerText = device.Suffix;
					xmlElement2.AppendChild(xmlElement3);
				}
				if (device.NeedAccount.HasValue)
				{
					XmlElement xmlElement4 = xmlDocument.CreateElement("NeedAccount");
					xmlElement4.InnerText = device.NeedAccount.ToString();
					xmlElement2.AppendChild(xmlElement4);
				}
				if (device.Account != null && !string.IsNullOrEmpty(device.Account))
				{
					XmlElement xmlElement5 = xmlDocument.CreateElement("Account");
					xmlElement5.InnerText = device.Account;
					xmlElement2.AppendChild(xmlElement5);
				}
				if (device.Pwd != null && !string.IsNullOrEmpty(device.Pwd))
				{
					XmlElement xmlElement6 = xmlDocument.CreateElement("Pwd");
					xmlElement6.InnerText = device.Pwd;
					xmlElement2.AppendChild(xmlElement6);
				}
				if (device.Rack.HasValue)
				{
					XmlElement xmlElement7 = xmlDocument.CreateElement("Rack");
					xmlElement7.InnerText = device.Rack.ToString();
					xmlElement2.AppendChild(xmlElement7);
				}
				if (device.Slot.HasValue)
				{
					XmlElement xmlElement8 = xmlDocument.CreateElement("Slot");
					xmlElement8.InnerText = device.Slot.ToString();
					xmlElement2.AppendChild(xmlElement8);
				}
				if (device.DataFormat != null)
				{
					XmlElement xmlElement9 = xmlDocument.CreateElement("DataFormat");
					xmlElement9.InnerText = device.DataFormat.ToString();
					xmlElement2.AppendChild(xmlElement9);
				}
				if (device.AddressStartWithZero.HasValue)
				{
					XmlElement xmlElement10 = xmlDocument.CreateElement("AddressStartWithZero");
					xmlElement10.InnerText = device.AddressStartWithZero.ToString();
					xmlElement2.AppendChild(xmlElement10);
				}
				if (device.IsStringReverse.HasValue)
				{
					XmlElement xmlElement11 = xmlDocument.CreateElement("IsStringReverse");
					xmlElement11.InnerText = device.IsStringReverse.ToString();
					xmlElement2.AppendChild(xmlElement11);
				}
				if (device.Station.HasValue)
				{
					XmlElement xmlElement12 = xmlDocument.CreateElement("Station");
					xmlElement12.InnerText = device.Station.ToString();
					xmlElement2.AppendChild(xmlElement12);
				}
				if (device.ComPort != null)
				{
					XmlElement xmlElement13 = xmlDocument.CreateElement("ComPort");
					xmlElement13.InnerText = device.ComPort.ToString();
					xmlElement2.AppendChild(xmlElement13);
				}
				if (device.BaudRate.HasValue)
				{
					XmlElement xmlElement14 = xmlDocument.CreateElement("BaudRate");
					xmlElement14.InnerText = device.BaudRate.ToString();
					xmlElement2.AppendChild(xmlElement14);
				}
				if (device.DataBits.HasValue)
				{
					XmlElement xmlElement15 = xmlDocument.CreateElement("DataBits");
					xmlElement15.InnerText = device.DataBits.ToString();
					xmlElement2.AppendChild(xmlElement15);
				}
				if (device.StopBits.HasValue)
				{
					XmlElement xmlElement16 = xmlDocument.CreateElement("StopBits");
					xmlElement16.InnerText = device.StopBits.ToString();
					xmlElement2.AppendChild(xmlElement16);
				}
				if (device.Parity.HasValue)
				{
					XmlElement xmlElement17 = xmlDocument.CreateElement("Parity");
					xmlElement17.InnerText = device.Parity.ToString();
					xmlElement2.AppendChild(xmlElement17);
				}
				flag = true;
				break;
			}
		}
		if (!flag)
		{
			MessageBox.Show("未在配置文件中找到对应的节点", "异常", MessageBoxButtons.OK, MessageBoxIcon.Hand);
			return;
		}
		xmlDocument.Save(Common.CONFIG_FILE_FULL_PATH);
		TreeNode treeNode = tvDevices.Nodes.Find(device.Id.ToString(), searchAllChildren: true)[0];
		treeNode.Text = device.ShowName;
		treeNode.ToolTipText = device.Desc;
		treeNode.Tag = device;
		treeNode.ImageIndex = 0;
		treeNode.SelectedImageIndex = 0;
		tvDevices.SelectedNode = treeNode;
		Device device2 = DEVICES.FirstOrDefault((Device t) => t.Id == device.Id);
		if (device2 != null)
		{
			int index = DEVICES.IndexOf(device2);
			DEVICES[index] = device;
		}
	}

	/// <summary>
	/// 上移
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void btnUp_Click(object sender, EventArgs e)
	{
		if (tvDevices.SelectedNode == null)
		{
			return;
		}
		TreeNode selectedNode = tvDevices.SelectedNode;
		int index = tvDevices.SelectedNode.Index;
		if (index == 0)
		{
			return;
		}
		Device device = (Device)selectedNode.Tag;
		XmlDocument xmlDocument = new XmlDocument();
		xmlDocument.Load(Common.CONFIG_FILE_FULL_PATH);
		XmlElement documentElement = xmlDocument.DocumentElement;
		XmlElement xmlElement = (XmlElement)documentElement.SelectSingleNode("Devices");
		bool flag = false;
		foreach (XmlNode item in xmlElement.SelectNodes("Device"))
		{
			Guid guid = new Guid(item.Attributes["Id"].Value);
			if (guid == device.Id)
			{
				flag = true;
				xmlElement.InsertBefore(item, xmlElement.ChildNodes[index - 1]);
				break;
			}
		}
		if (!flag)
		{
			MessageBox.Show("未在配置文件中找到对应的节点", "异常", MessageBoxButtons.OK, MessageBoxIcon.Hand);
			return;
		}
		xmlDocument.Save(Common.CONFIG_FILE_FULL_PATH);
		tvDevices.Nodes.Remove(selectedNode);
		tvDevices.Nodes.Insert(index - 1, selectedNode);
		tvDevices.SelectedNode = selectedNode;
		DEVICES.Remove(device);
		DEVICES.Insert(index - 1, device);
	}

	/// <summary>
	/// 下移
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void btnDown_Click(object sender, EventArgs e)
	{
		if (tvDevices.SelectedNode == null)
		{
			return;
		}
		TreeNode selectedNode = tvDevices.SelectedNode;
		int index = tvDevices.SelectedNode.Index;
		if (index == tvDevices.Nodes.Count - 1)
		{
			return;
		}
		Device device = (Device)selectedNode.Tag;
		XmlDocument xmlDocument = new XmlDocument();
		xmlDocument.Load(Common.CONFIG_FILE_FULL_PATH);
		XmlElement documentElement = xmlDocument.DocumentElement;
		XmlElement xmlElement = (XmlElement)documentElement.SelectSingleNode("Devices");
		bool flag = false;
		foreach (XmlNode item in xmlElement.SelectNodes("Device"))
		{
			Guid guid = new Guid(item.Attributes["Id"].Value);
			if (guid == device.Id)
			{
				flag = true;
				xmlElement.InsertAfter(item, xmlElement.ChildNodes[index + 1]);
				break;
			}
		}
		if (!flag)
		{
			MessageBox.Show("未在配置文件中找到对应的节点", "异常", MessageBoxButtons.OK, MessageBoxIcon.Hand);
			return;
		}
		xmlDocument.Save(Common.CONFIG_FILE_FULL_PATH);
		tvDevices.Nodes.Remove(selectedNode);
		tvDevices.Nodes.Insert(index + 1, selectedNode);
		tvDevices.SelectedNode = selectedNode;
		DEVICES.Remove(device);
		DEVICES.Insert(index + 1, device);
	}

	/// <summary>
	/// 仅在右键单击Node时展开菜单
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void tvDevices_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
	{
		Point pt = new Point(e.X, e.Y);
		TreeNode nodeAt = tvDevices.GetNodeAt(pt);
		if (nodeAt != null && e.Button == MouseButtons.Right)
		{
			tvDevices.SelectedNode = nodeAt;
			tvDevices.SelectedNode.ContextMenuStrip = cmsDevice;
		}
	}

	/// <summary>
	/// 左键双击时-编辑设备
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void tvDevices_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
	{
		if (e.Button == MouseButtons.Left)
		{
			ShowEditDeviceForm();
		}
	}

	/// <summary>
	/// 按下Del键时-删除设备
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void tvDevices_KeyDown(object sender, KeyEventArgs e)
	{
		if (e.KeyCode == Keys.Delete)
		{
			DeleteDevice();
		}
	}

	/// <summary>
	/// Edit Device
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void tsmiEdit_Click(object sender, EventArgs e)
	{
		ShowEditDeviceForm();
	}

	/// <summary>
	/// Delete Device
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void tsmiDel_Click(object sender, EventArgs e)
	{
		DeleteDevice();
	}

	/// <summary>
	/// FormClosing
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void DeviceMgrForm_FormClosing(object sender, FormClosingEventArgs e)
	{
		BW_UPDATE_DEVICE_STATUS.CancelAsync();
	}

	/// <summary>
	/// 开启设备延迟超限的日志
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void tsmiStartDelayLog_Click(object sender, EventArgs e)
	{
		if (!MainForm.IS_DELAYLOGING)
		{
			tsmiStartDelayLog.Enabled = false;
			MainForm.StartDelayLog();
			tsmiStopDelayLog.Enabled = true;
		}
	}

	/// <summary>
	/// 关闭设备延迟超限的日志
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void tsmiStopDelayLog_Click(object sender, EventArgs e)
	{
		if (MainForm.IS_DELAYLOGING)
		{
			tsmiStopDelayLog.Enabled = false;
			MainForm.StopDelayLog();
			tsmiStartDelayLog.Enabled = true;
		}
	}

	/// <summary>
	/// 延迟超限日志的相关配置
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void tsmiSetting_Click(object sender, EventArgs e)
	{
		DelayLogSettingForm delayLogSettingForm = new DelayLogSettingForm
		{
			Icon = base.Icon,
			StartPosition = FormStartPosition.CenterParent
		};
		delayLogSettingForm.Save += DelayLogSettingForm_Save;
		delayLogSettingForm.ShowDialog();
	}

	private void DelayLogSettingForm_Save(List<Device> devices)
	{
	}

	/// <summary>
	/// Clean up any resources being used.
	/// </summary>
	/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
	protected override void Dispose(bool disposing)
	{
		if (disposing && components != null)
		{
			components.Dispose();
		}
		base.Dispose(disposing);
	}

	/// <summary>
	/// Required method for Designer support - do not modify
	/// the contents of this method with the code editor.
	/// </summary>
	private void InitializeComponent()
	{
		this.components = new System.ComponentModel.Container();
		System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(WIT.DAQ.Core.Forms.DeviceMgrForm));
		this.cmsDevice = new System.Windows.Forms.ContextMenuStrip(this.components);
		this.tsmiEdit = new System.Windows.Forms.ToolStripMenuItem();
		this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
		this.tsmiDel = new System.Windows.Forms.ToolStripMenuItem();
		this.tvDevices = new System.Windows.Forms.TreeView();
		this.imageList = new System.Windows.Forms.ImageList(this.components);
		this.btnUp = new System.Windows.Forms.Button();
		this.btnDown = new System.Windows.Forms.Button();
		this.btnDel = new System.Windows.Forms.Button();
		this.btnAdd = new System.Windows.Forms.Button();
		this.toolStrip1 = new System.Windows.Forms.ToolStrip();
		this.tsbtnDelayLog = new System.Windows.Forms.ToolStripDropDownButton();
		this.tsmiStartDelayLog = new System.Windows.Forms.ToolStripMenuItem();
		this.tsmiStopDelayLog = new System.Windows.Forms.ToolStripMenuItem();
		this.tsmiSetting = new System.Windows.Forms.ToolStripMenuItem();
		this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
		this.cmsDevice.SuspendLayout();
		this.toolStrip1.SuspendLayout();
		base.SuspendLayout();
		this.cmsDevice.Items.AddRange(new System.Windows.Forms.ToolStripItem[3] { this.tsmiEdit, this.toolStripSeparator1, this.tsmiDel });
		this.cmsDevice.Name = "cmsDevices";
		this.cmsDevice.Size = new System.Drawing.Size(125, 54);
		this.tsmiEdit.Image = global::WIT_DAQ_Core_Properties_Resour.edit_black;
		this.tsmiEdit.Name = "tsmiEdit";
		this.tsmiEdit.Size = new System.Drawing.Size(124, 22);
		this.tsmiEdit.Text = "编辑设备";
		this.tsmiEdit.Click += new System.EventHandler(tsmiEdit_Click);
		this.toolStripSeparator1.Name = "toolStripSeparator1";
		this.toolStripSeparator1.Size = new System.Drawing.Size(121, 6);
		this.tsmiDel.Image = global::WIT_DAQ_Core_Properties_Resour.del_black;
		this.tsmiDel.Name = "tsmiDel";
		this.tsmiDel.Size = new System.Drawing.Size(124, 22);
		this.tsmiDel.Text = "删除设备";
		this.tsmiDel.Click += new System.EventHandler(tsmiDel_Click);
		this.tvDevices.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right;
		this.tvDevices.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
		this.tvDevices.ImageIndex = 0;
		this.tvDevices.ImageList = this.imageList;
		this.tvDevices.ItemHeight = 15;
		this.tvDevices.Location = new System.Drawing.Point(4, 28);
		this.tvDevices.Name = "tvDevices";
		this.tvDevices.SelectedImageIndex = 0;
		this.tvDevices.ShowNodeToolTips = true;
		this.tvDevices.Size = new System.Drawing.Size(340, 430);
		this.tvDevices.TabIndex = 4;
		this.tvDevices.NodeMouseClick += new System.Windows.Forms.TreeNodeMouseClickEventHandler(tvDevices_NodeMouseClick);
		this.tvDevices.NodeMouseDoubleClick += new System.Windows.Forms.TreeNodeMouseClickEventHandler(tvDevices_NodeMouseDoubleClick);
		this.tvDevices.KeyDown += new System.Windows.Forms.KeyEventHandler(tvDevices_KeyDown);
		this.imageList.ImageStream = (System.Windows.Forms.ImageListStreamer)resources.GetObject("imageList.ImageStream");
		this.imageList.TransparentColor = System.Drawing.Color.Transparent;
		this.imageList.Images.SetKeyName(0, "circle-grey.png");
		this.imageList.Images.SetKeyName(1, "circle-green.png");
		this.imageList.Images.SetKeyName(2, "circle-red.png");
		this.imageList.Images.SetKeyName(3, "circle_yellow.png");
		this.btnUp.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right;
		this.btnUp.BackgroundImage = (System.Drawing.Image)resources.GetObject("btnUp.BackgroundImage");
		this.btnUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
		this.btnUp.Location = new System.Drawing.Point(350, 136);
		this.btnUp.Name = "btnUp";
		this.btnUp.Size = new System.Drawing.Size(30, 30);
		this.btnUp.TabIndex = 2;
		this.btnUp.UseVisualStyleBackColor = true;
		this.btnUp.Click += new System.EventHandler(btnUp_Click);
		this.btnDown.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right;
		this.btnDown.BackgroundImage = (System.Drawing.Image)resources.GetObject("btnDown.BackgroundImage");
		this.btnDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
		this.btnDown.Location = new System.Drawing.Point(350, 172);
		this.btnDown.Name = "btnDown";
		this.btnDown.Size = new System.Drawing.Size(30, 30);
		this.btnDown.TabIndex = 3;
		this.btnDown.UseVisualStyleBackColor = true;
		this.btnDown.Click += new System.EventHandler(btnDown_Click);
		this.btnDel.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right;
		this.btnDel.BackgroundImage = global::WIT_DAQ_Core_Properties_Resour.del_black;
		this.btnDel.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
		this.btnDel.Location = new System.Drawing.Point(350, 64);
		this.btnDel.Name = "btnDel";
		this.btnDel.Size = new System.Drawing.Size(30, 30);
		this.btnDel.TabIndex = 1;
		this.btnDel.UseVisualStyleBackColor = true;
		this.btnDel.Click += new System.EventHandler(btnDel_Click);
		this.btnAdd.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right;
		this.btnAdd.BackgroundImage = (System.Drawing.Image)resources.GetObject("btnAdd.BackgroundImage");
		this.btnAdd.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
		this.btnAdd.Location = new System.Drawing.Point(350, 28);
		this.btnAdd.Name = "btnAdd";
		this.btnAdd.Size = new System.Drawing.Size(30, 30);
		this.btnAdd.TabIndex = 0;
		this.btnAdd.UseVisualStyleBackColor = true;
		this.btnAdd.Click += new System.EventHandler(btnAdd_Click);
		this.toolStrip1.AutoSize = false;
		this.toolStrip1.Dock = System.Windows.Forms.DockStyle.None;
		this.toolStrip1.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
		this.toolStrip1.ImeMode = System.Windows.Forms.ImeMode.NoControl;
		this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[1] { this.tsbtnDelayLog });
		this.toolStrip1.Location = new System.Drawing.Point(3, 0);
		this.toolStrip1.Name = "toolStrip1";
		this.toolStrip1.Size = new System.Drawing.Size(391, 25);
		this.toolStrip1.TabIndex = 6;
		this.toolStrip1.Text = "toolStrip1";
		this.tsbtnDelayLog.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[4] { this.tsmiStartDelayLog, this.tsmiStopDelayLog, this.toolStripSeparator2, this.tsmiSetting });
		this.tsbtnDelayLog.Image = global::WIT_DAQ_Core_Properties_Resour.warning_red;
		this.tsbtnDelayLog.ImageTransparentColor = System.Drawing.Color.Magenta;
		this.tsbtnDelayLog.Name = "tsbtnDelayLog";
		this.tsbtnDelayLog.Size = new System.Drawing.Size(109, 22);
		this.tsbtnDelayLog.Text = "记录设备延迟";
		this.tsbtnDelayLog.ToolTipText = "当设备延迟超出设定值时，记录日志";
		this.tsmiStartDelayLog.Name = "tsmiStartDelayLog";
		this.tsmiStartDelayLog.Size = new System.Drawing.Size(180, 22);
		this.tsmiStartDelayLog.Text = "开启";
		this.tsmiStartDelayLog.Click += new System.EventHandler(tsmiStartDelayLog_Click);
		this.tsmiStopDelayLog.Name = "tsmiStopDelayLog";
		this.tsmiStopDelayLog.Size = new System.Drawing.Size(180, 22);
		this.tsmiStopDelayLog.Text = "关闭";
		this.tsmiStopDelayLog.Click += new System.EventHandler(tsmiStopDelayLog_Click);
		this.tsmiSetting.Image = global::WIT_DAQ_Core_Properties_Resour.setting;
		this.tsmiSetting.Name = "tsmiSetting";
		this.tsmiSetting.Size = new System.Drawing.Size(180, 22);
		this.tsmiSetting.Text = "配置";
		this.tsmiSetting.Click += new System.EventHandler(tsmiSetting_Click);
		this.toolStripSeparator2.Name = "toolStripSeparator2";
		this.toolStripSeparator2.Size = new System.Drawing.Size(177, 6);
		base.AutoScaleDimensions = new System.Drawing.SizeF(6f, 12f);
		base.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
		base.ClientSize = new System.Drawing.Size(384, 461);
		base.Controls.Add(this.toolStrip1);
		base.Controls.Add(this.btnUp);
		base.Controls.Add(this.btnDown);
		base.Controls.Add(this.btnDel);
		base.Controls.Add(this.btnAdd);
		base.Controls.Add(this.tvDevices);
		base.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
		base.MaximizeBox = false;
		base.Name = "DeviceMgrForm";
		this.Text = "设备列表 - 图标仅表示IP通讯是否正常";
		base.FormClosing += new System.Windows.Forms.FormClosingEventHandler(DeviceMgrForm_FormClosing);
		base.Load += new System.EventHandler(DeviceForm_Load);
		base.Shown += new System.EventHandler(DeviceMgrForm_Shown);
		this.cmsDevice.ResumeLayout(false);
		this.toolStrip1.ResumeLayout(false);
		this.toolStrip1.PerformLayout();
		base.ResumeLayout(false);
	}
}
